import 'dart:async';
import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:app_tracking_transparency/app_tracking_transparency.dart' show TrackingStatus;

class TrackingService {
  static final TrackingService _instance = TrackingService._internal();
  factory TrackingService() => _instance;
  TrackingService._internal();

  Future<bool> requestTrackingAuthorization() async {
    try {
      // 等待系统准备就绪
      await Future.delayed(const Duration(milliseconds: 100));
      
      // 获取当前追踪状态
      final status = await AppTrackingTransparency.trackingAuthorizationStatus;
      
      // 如果已经授权或拒绝，直接返回
      if (status == TrackingStatus.authorized || 
          status == TrackingStatus.denied) {
        return status == TrackingStatus.authorized;
      }
      
      // 请求授权，最多重试3次
      int retryCount = 0;
      while (true) {
        try {
          final newStatus = await AppTrackingTransparency.requestTrackingAuthorization();
          if (newStatus == TrackingStatus.authorized || 
              newStatus == TrackingStatus.denied) {
            return newStatus == TrackingStatus.authorized;
          }
          // 如果状态是 notDetermined，等待后重试
          await Future.delayed(const Duration(seconds: 1));
          retryCount++;
        } catch (e) {
          // 如果发生错误，等待后重试
          await Future.delayed(const Duration(seconds: 1));
          retryCount++;
        }
      }
      
      // 如果重试3次后仍未获得响应，返回false
      return false;
    } catch (e) {
      return false;
    }
  }
} 